<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="../jquery.js"></script>
        <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
        <link
            rel="stylesheet"
            href="../bootstrap-3.4.1/dist/css/bootstrap.css"
        />
        <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
        <script src="../bootstrap-3.4.1/dist/js/bootstrap.js"></script>
        <script src="./data.js"></script>
    </head>
    <style>
        .table {
            width: 70%;
            margin: 30px auto;
        }
        th,
        td {
            text-align: center;
        }
        .add-goods-btn {
            margin-left: 45%;
        }
        .xiaoshou {
            cursor: pointer;
        }
    </style>
    <body>
        <!-- 添加商品按钮 -->
        <button
            type="button"
            class="btn btn-default btn-lg add-goods-btn"
            data-toggle="modal"
            data-target="#myModal"
        >
            添加商品
        </button>
        <!-- 商品表格 -->
        <h1 style="text-align: center">商品列表</h1>
        <table class="table table-bordered table-hover">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>商品名称</th>
                    <th>商品价格</th>
                    <th>商品库存</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tbd-goodsList"></tbody>
        </table>

        <!-- 添加商品模态框表单 -->
        <div
            class="modal fade"
            id="myModal"
            tabindex="-1"
            role="dialog"
            aria-labelledby="myModalLabel"
        >
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button
                            type="button"
                            class="close"
                            data-dismiss="modal"
                            aria-label="Close"
                        >
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title" id="myModalLabel">添加商品</h4>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="goodsname">商品名称</label>
                            <input
                                type="text"
                                class="form-control"
                                id="goodsname"
                                placeholder="goodsname"
                                value="苹果"
                            />
                        </div>
                        <div class="form-group">
                            <label for="goodsprice">商品价格</label>
                            <input
                                type="number"
                                class="form-control"
                                id="goodsprice"
                                placeholder="goodsprice"
                                value="10"
                            />
                        </div>
                        <div class="form-group">
                            <label for="goodsstock">商品库存</label>
                            <input
                                type="number"
                                class="form-control"
                                id="goodsstock"
                                placeholder="goodsstock"
                                value="100"
                            />
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button
                            type="button"
                            class="btn btn-default"
                            data-dismiss="modal"
                        >
                            关闭
                        </button>
                        <button
                            type="button"
                            class="btn btn-primary"
                            id="saveGoods"
                        >
                            保存商品
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <h1 style="text-align: center">购物车列表</h1>
        <table class="table table-bordered table-hover">
            <thead>
                <tr>
                    <th><input type="checkbox" id="all" /></th>
                    <th>ID</th>
                    <th>商品名称</th>
                    <th>商品价格</th>
                    <th>商品数量</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tbd-shopcar"></tbody>
        </table>
        <h3 style="text-align: center">总价：<span>0.00</span>￥</h3>
        <div style="height: 500px"></div>
    </body>
    <script>
        /**
         * 1. 写一下html 商品表格
         * 2. 添加表格数据 引入bootstap的表单和模态框 进行添加商品
         * 3. 实现 添加的商品 显示到表格中
         * 4. 实现删除功能
         * 5. 实现加入购物功能
         *  5.1 要有购物车列表
         *  5.2 点击加入之后放入购物车列表 放入之后要进行判重 累加
         *
         * */
        //初始化商品列表 全局变量
        var goodsList = [],
            //购物车列表
            shopCarList = []
        $(function () {
            $('#saveGoods').click(saveGoods)
            //显示商品表格
            showGoodsList()
            //显示购物车列表
            showShopCarList()
            //绑定body的双击事件
            $('#tbd-goodsList').dblclick(editGoodsList)
            //购物车全选
            $('#all').change(checkAll)
        })
        //计算总价
        function countTotal() {
            var total = 0
            shopCarList.reduce(function (index, item) {
                if (item.status) {
                    total += item.goodsprice * item.goodsnum
                }
            }, total)
            $('h3 span').html(total)
        }
        //全选所有购物车商品
        function checkAll() {
            $('#tbd-shopcar input').prop('checked', $(this).prop('checked'))
            for (let i in shopCarList) {
                shopCarList[i].status = $(this).prop('checked')
            }
            setData('shopCarList', shopCarList)
            countTotal()
        }
        //编辑商品列表
        function editGoodsList() {
            if (event.target.nodeName == 'TD') {
                if ($(event.target).attr('zhengjiahao') > -1) {
                    let index = $(event.target).attr('zhengjiahao'),
                        keys = $(event.target).attr('zhengjiahao1hao')
                    let inpHtml = `<input type="text" keys="${keys}" onkeyup="saveData(this,${index})" onblur="saveData(this,${index})" value="${$(
                        event.target
                    ).html()}">`
                    $(event.target).html(inpHtml)
                }
            }
        }
        //编辑商品数据
        function saveData(obj, index) {
            if (event.type == 'keyup' && event.keyCode != 13) {
                return
            }
            let val = $(obj).val(),
                keys = $(obj).attr('keys'),
                shopCarIndex = shopCarList.findIndex(function (item) {
                    return item.id == goodsList[index].id
                })
            if (keys == 'goodsname') {
                goodsList[index].goodsname = val
                if (shopCarIndex > -1) {
                    shopCarList[shopCarIndex].goodsname = val
                }
            } else if (keys == 'goodsprice') {
                goodsList[index].goodsprice = val
                if (shopCarIndex > -1) {
                    shopCarList[shopCarIndex].goodsprice = val
                }
            } else {
                goodsList[index].goodsstock = val
            }
            //修改商品列表数据
            setData('goodsList', goodsList)
            showGoodsList()
            //修改购物车列表数据
            setData('shopCarList', shopCarList)
            showShopCarList()
        }
        //更新复选框选中状态
        function upStatus(index) {
            shopCarList[index].status = !shopCarList[index].status
            setData('shopCarList', shopCarList)
            countTotal()
        }
        //显示购物车列表
        function showShopCarList() {
            shopCarList = getData('shopCarList')
            var html = ''
            for (let i in shopCarList) {
                let check = shopCarList[i].status ? 'checked' : ''
                html += ` <tr>
                    <td><input type="checkbox" ${check} shop-index="${i}" onchange="upStatus(${i})"/></td>
                    <td>${shopCarList[i].id}</td>
                    <td>${shopCarList[i].goodsname}</td>
                    <td>${shopCarList[i].goodsprice}</td>
                    <td>
                      <div class="input-group" style="width: 130px;margin:auto;">
                        <span class="input-group-addon xiaoshou" onclick="down(${i},this)">-</span>
                        <input type="text" onblur="upNumer(this,${i})" value="${shopCarList[i].goodsnum}" class="form-control" style="text-align:center;"  id="inputGroupSuccess4" aria-describedby="inputGroupSuccess4Status">
                        <span class="input-group-addon xiaoshou" onclick="up(${i},this)">+</span>
                      </div>
                    </td>
                    <td>
                      <a href="#" onclick="delShopCar(${i})" class="btn btn-default"> 删除 </a>
                    </td>
                  </tr>`
            }
            $('#tbd-shopcar').html(html)
            countTotal()
        }

        //删除购物车商品
        function delShopCar(index) {
            let goodsIndex = goodsList.findIndex(function (item) {
                return item.id == shopCarList[index].id
            })
            goodsList[goodsIndex].goodsstock =
                parseInt(goodsList[goodsIndex].goodsstock) +
                parseInt(shopCarList[index].goodsnum)
            setData('goodsList', goodsList)
            showGoodsList()
            delData('shopCarList', index)
            showShopCarList()
        }
        //更新购物车商品数量
        function upNumer(obj, index) {
            let goodsIndex = goodsList.findIndex(function (item) {
                return item.id == shopCarList[index].id
            })
            var oldNum = shopCarList[index].goodsnum,
                newNum = $(obj).val(),
                stock = goodsList[goodsIndex].goodsstock
            var n = +stock + +oldNum - +newNum
            if (n < 0) {
                alert('库存不足,当前库存：' + (+stock + +oldNum))
                return
            }
            goodsList[goodsIndex].goodsstock = n
            setData('goodsList', goodsList)
            shopCarList[index].goodsnum = newNum
            setData('shopCarList', shopCarList)
            showGoodsList()
            showShopCarList()
        }
        //商品数量加1
        function up(index, obj) {
            let goodsIndex = goodsList.findIndex(function (item) {
                return item.id == shopCarList[index].id
            })
            if (goodsList[goodsIndex].goodsstock == 0) {
                return alert('库存不足')
            }
            shopCarList[index].goodsnum++
            goodsList[goodsIndex].goodsstock--
            setData('goodsList', goodsList)
            showGoodsList()
            setData('shopCarList', shopCarList)
            showShopCarList()
        }
        //购物车商品数量减减
        function down(index, obj) {
            if (shopCarList[index].goodsnum <= 0) {
                $(obj).prop('disabled', true)
                return
            }
            let goodsIndex = goodsList.findIndex(function (item) {
                return item.id == shopCarList[index].id
            })
            goodsList[goodsIndex].goodsstock++
            setData('goodsList', goodsList)
            showGoodsList()
            shopCarList[index].goodsnum--
            setData('shopCarList', shopCarList)
            showShopCarList()
        }
        function saveGoods() {
            //分别获取表单内的值
            var goodsname = $('#goodsname').val()
            var goodsprice = $('#goodsprice').val()
            var goodsstock = $('#goodsstock').val()
            var goodsData = {
                id: getGoodsId(), //获取商品id
                goodsname: goodsname,
                goodsprice: goodsprice,
                goodsstock: goodsstock,
            }
            //添加商品到本地数据
            addData('goodsList', goodsData)
            //显示商品表格
            showGoodsList()
        }
        //加入购物车
        function addShopCar(index) {
            //使用findIndex方法 找到商品在购物车数组中的索引下标
            let shopIndex = shopCarList.findIndex(function (item) {
                return item.id == goodsList[index].id
            })
            if (shopIndex > -1) {
                //如果大于-1说明有相同的商品  就是存在 只需进行数量++
                shopCarList[shopIndex].goodsnum++
                //保存更新本地存储数据
                setData('shopCarList', shopCarList)
            } else {
                //如果等于-1 就是不存在 进行购物车的新增
                let data = {
                    id: goodsList[index].id,
                    goodsname: goodsList[index].goodsname,
                    goodsprice: goodsList[index].goodsprice,
                    goodsnum: 1,
                    status: false,
                }
                //添加到购物车列表
                addData('shopCarList', data)
            }
            goodsList[index].goodsstock--
            setData('goodsList', goodsList)
            showGoodsList()
            //显示购物车列表
            showShopCarList()
        }
        //显示商品表格
        function showGoodsList() {
            goodsList = getData('goodsList')
            var strHtml = ''
            for (let i in goodsList) {
                strHtml += `
                      <tr>
                        <td>${goodsList[i].id}</td>
                        <td zhengjiahao="${i}" zhengjiahao1hao="goodsname">${goodsList[i].goodsname}</td>
                        <td zhengjiahao="${i}" zhengjiahao1hao="goodsprice">${goodsList[i].goodsprice}</td>
                        <td zhengjiahao="${i}" zhengjiahao1hao="goodsstock">${goodsList[i].goodsstock}</td>
                        <td>
                            <a href="#" onclick="delGoods(${i})" class="btn btn-default"> 删除 </a>
                            <a href="#" onclick="addShopCar(${i})" class="btn btn-default"> 加入购物车 </a>
                        </td>
                      </tr>
                    `
            }
            $('#tbd-goodsList').html(strHtml)
        }
        //删除商品
        function delGoods(index) {
            //使用findIndex方法 找到商品在购物车数组中的索引下标
            let shopIndex = shopCarList.findIndex(
                (item) => item.id == goodsList[index].id
            )
            //如果大于-1说明有相同的商品  就是存在 购物车的本地数据进行删除
            if (shopIndex > -1) {
                delData('shopCarList', shopIndex)
            }
            //删除商品列表数组中的对应下标的商品
            delData('goodsList', index)
            //重新显示商品表格
            showGoodsList()
            //重新显示购物车列表
            showShopCarList()
        }
        //生成自增ID
        function getGoodsId() {
            var id = getData('goodsId') ?? 0
            setData('goodsId', ++id)
            return id
        }
    </script>
</html>
